require('babel-core/register');

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const webpack = require('webpack');

const config = require('../config');
const webpackConfig = require('../build/webpack/' + config.env);

const middleware = ['router', 'proxy', 'mock', 'static', 'error'];
const app = module.exports = express();
const compiler = webpack(webpackConfig);

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));


const paths = config.utils_paths;
var content = '';
var globals = config.globals;
globals.process = {
    env: {
        NODE_ENV: globals.NODE_ENV
    }
};
Object.keys(globals).forEach(function (key, index) {
    if (key === 'process.env') return;
    content += 'window.' + key + '=' + JSON.stringify(globals[key]) + ';\n';
});
app.set('content', content);
// lazy load middlewares
middleware.forEach(function (m) {
    middleware.__defineGetter__(m, function () {
        return require('./middleware/' + m);
    });
});

process.on('uncaughtException', function (err) {
    (app.get('logger') || console).error('Uncaught exception:\n', err.stack);
});
app.use(bodyParser.json());

app.use('/proxy', middleware.proxy(config.api_target));

app.use(middleware.router({
    index: path.join(__dirname, 'index.html')
}));
app.use(middleware.static(paths.dist('')));
app.use(middleware.error());

if (require.main === module) {
    app.listen(config.server_port, function () {
        console.log('[%s] Express server listening on port %d', app.get('env').toUpperCase(), config.server_port);
    });
}

